<template>
  <div class="w">
    <div class="left">
      <div>
        <!--得到的 questions 的内容 最终会以该div显示出来-->
        <div class="problem_detail">
          <h3>题目{{ current_question_num + 1 }}：{{ questions[current_question_num].Title }}</h3>
          <h3>题目描述</h3>
          <p class="post_content">{{ questions[current_question_num].Content }}</p>
          <br>
          <h3>输入格式</h3>
          <div class="post_content" style="margin-left: 2em">
            <pre>{{ questions[current_question_num].InputFormat }}</pre>
          </div>
          <br>
          <h3>样例数据</h3>
          <p class="post_content">输入</p>
          <ul class="input_output">
            <li v-for="k in questions[current_question_num].InputExample.length">
              {{ questions[current_question_num].InputExample[k - 1] }}
            </li>
          </ul>
          <p class="post_content">输出</p>
          <ul class="input_output">
            <li v-for="j in questions[current_question_num].OutputExample.length">
              {{ questions[current_question_num].OutputExample[j - 1] }}
            </li>
          </ul>
          <br>
          <h3>备注</h3>
          <p class="post_content">{{ questions[current_question_num].Remark }}</p>
        </div>
      </div>

    </div>

    <div class="right">
      <ul>
        <li v-for="(i, index) in interview_question_num" class="interviewer_list" @click="question_change(i)">
          <span class="index" :style="random_rgb()">{{ index + 1 }}</span>
          <span class="simple_message">{{ questions[i - 1].Title }}</span>
        </li>
      </ul>
      <br>
      <br>
      <br>
      <el-button type="primary" plain @click="code_submit">保存作答</el-button>
      <el-button type="warning" plain @click="final_submit">确认交卷</el-button>
      <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose">
        <span>这是一段信息</span>
        <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="final_submit">确 定</el-button>
  </span>
      </el-dialog>
    </div>


    <div class="left" style="width: 100%">
      <!-- or to manually control the datasynchronization（或者手动控制数据流，需要像这样手动监听changed事件） -->
      <el-select v-model="Svalue" @change="change_high_light" placeholder="请选择编程语言">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
          style="padding-left: 10px">
        </el-option>
      </el-select>
      <el-button type="primary" @click="update_answer">上传<i class="el-icon-upload el-icon--right"></i></el-button>
      <br>
      <br>
      <el-alert v-show="isFinalSubmit"
        title="此为最终答案"
        type="warning"
                :closable="false"
                effect="dark"></el-alert>
      <codemirror ref="myCm"
                  :value="code"
                  :options="cmOptions"
                  @ready="onCmReady"
                  @focus="onCmFocus"
                  @input="onCmCodeChange"
                  style="margin-top: 10px">
      </codemirror>

      <button @click="btn" style="display:block;min-width:50px;margin:20px auto 0 auto;">Run</button>

    </div>
  </div>
</template>

<script>
import "codemirror/mode/javascript/javascript.js";
import "codemirror/theme/monokai.css";
import axios from "axios";
import qs from "qs";
import { Message } from "element-ui";

require("codemirror/mode/clike/clike.js");
require("codemirror/mode/javascript/javascript.js");
require("codemirror/mode/xml/xml.js");
require("codemirror/mode/vue/vue.js");
require("codemirror/mode/python/python.js");
require("codemirror/mode/css/css.js");
require("codemirror/mode/sql/sql.js");
require("codemirror/mode/shell/shell.js");

export default {
  name: "interview_page",
  data() {
    return {
      current_question_num: 0,
      interview_question_num: 2,
      dialogVisible: false,
      questions: [
        {
          QID: 1,
          Title: "输入两个整数，输出这两个数的积",
          Content: "输入两个整数，输出这两个数的积",
          InputFormat: "补全 solve() 函数.\n" +
            "函数包含两个参数，a,b (−100000 ≤ a,b ≤ 100000)",
          InputExample: ["-1 1", "0 2", "-100000 100000"],
          OutputExample: ["-1", "0", "-10000000000"],
          Remark: "本题为函数式编程，请使用 JavaScript++ 语言完成函数"
        },
        {
          QID: 1,
          Title: "输入两个整数，输出这两个数的积.",
          Content: "输入两个整数，输出这两个数的积",
          InputFormat: "补全 solve() 函数.\n" +
            "函数包含两个参数，a,b (−100000 ≤ a,b ≤ 100000)",
          InputExample: ["-1 1", "0 2", "-100000 100000"],
          OutputExample: ["-1", "0", "-10000000000"],
          Remark: "本题为函数式编程，请使用 JavaScript 语言完成函数"
        }
      ],
      options: [{
        value: "javascript",
        label: "javascript"
      }, {
        value: "xml",
        label: "xml"
      }, {
        value: "vue",
        label: "vue"
      }, {
        value: "python",
        label: "python"
      }, {
        value: "sql",
        label: "sql"
      }, {
        value: "shell",
        label: "shell"
      }, {
        value: "clike",
        label: "c++"
      }
      ],
      Svalue: "javascript",
      code: "function problemSolve(a) {\n\n\n" +
        "  return res;\n" +
        "}",
      answer: [
        {
          QID: 1,
          Answer: ""
        }
      ],
      codeV: "",
      lastLog: "abc",
      cmOptions: {
        // codemirror options
        tabSize: 4,
        mode: "text/javascript",
        theme: "monokai",
        lineNumbers: true,
        line: true,
        matchBrackets: true, // 匹配符号
        indentUnit: 2, // 缩进单位，默认2
        autoCloseTags: true, // 自动关闭标签
        autoCloseBrackets: true, // 自动输入括弧
        // more codemirror options, 更多 codemirror 的高级配置...
        extraKeys: {
          "Ctrl-Alt": "autocomplete",
          "Ctrl-Q": cm => {
            cm.foldCode(cm.getCursor());
          }
        } //智能提示
      },
      RID: "",
      isFinalSubmit:false,
    };
  },
  async mounted() {
    this.RID = this.$route.query.RID.toString();
    await axios({
      method: "post",
      url: "/room/get_questions",
      data:
        qs.stringify(
          {
            RID: this.$route.query.RID.toString()
          })

    })
      .then(res => {
        //获取数据
        console.log(res.data);
        if (res.data.err === 0) {
          this.questions = res.data.questions;
          this.interview_question_num = res.data.questions.length;

        }
        /*
                this.$message({
                  message:res.data,
                  type: 'success'
                });*/
      })
      .catch(function(error) {
        console.log(error);
      });
    this.answer = [];
    for (let i = 0; i < this.interview_question_num; i++) {
      let s = this.questions[i].InputExample;
      let varList = ["a", "b"];

      let a = "function problemSolve(";

      for (let ix = 0; ix < (varList.length); ix++) {
        /*alert(varList.length)*/
        a += varList[ix];
        if (ix < (varList.length - 1)) {
          a += ",";
        }
      }
      a += ") {\n\n\n" +
        "  return res;\n" +
        "}";
      console.log(this.questions[i].QID);
      let unit = {
        QID: this.questions[i].QID,
        Answer: a
      };
      this.answer.push(unit);
    }
    this.code = this.answer[0].Answer;
  },
  methods: {

    handleClose(done) {
      this.$confirm("此为最终提交，提交后无法更改")
        .then(_ => {
          done();
        })
        .catch(_ => {
        });
    },
    final_submit()//最终提交代码
    {

      this.dialogVisible = false;
    },
    code_submit()//提交代码
    {
      /*      let Array = [];
            for (let i = 0; i < this.questions.length; i++) {
              let qid=this.questions[i].QID;
              jsonA.qid= this.answer[i].Answer;
            }
            console.log(jsonA);

            */
      console.log(this.answer);
      let json = JSON.stringify(this.answer);
      console.log(json);
      axios({
        method: "post",
        url: "/room/submit",
        data:
          qs.stringify(
            {
              RID: this.RID,
              submittedCode: json,
              isFinalSubmit: false
            })
      })
        .then(res => {
          //获取数据
          console.log(res.data);
          if (res.data.errcode === 0) {

          } else if (res.data.errcode === -1) {
            Message.error("数据库连接失败");
          } else if (res.data.errcode === -2) {
            Message.error("数据库操作失败");
          } else {
            Message.error("未知错误");
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    // 进入该页面时 将所有的题目放入questions中 格式如 data 中样例所示
    random_rgb: function() {
      let R = Math.floor(Math.random() * 255);
      let G = Math.floor(Math.random() * 255);
      let B = Math.floor(Math.random() * 255);
      return {
        backgroundColor: "rgb(" + R + "," + G + "," + B + ")"
      };
    },
    update_answer() {
      axios({
        method: "post",
        url: "/room/get_submitted",
        data:
          qs.stringify(
            {
              RID: this.RID,
            })

      })
        .then(res => {
          //获取数据
          console.log(res.data);
          if (res.data.err === 0) {
            this.isFinalSubmit=res.data.isFinalSubmit;
            console.log(res.data.SubmittedCode);
            let json = JSON.parse(res.data.SubmittedCode);
            this.answer=eval(json);
            this.code=this.answer[this.current_question_num].Answer;
          } else if (res.data.errcode === -1) {
            Message.error("数据库连接失败");
          } else if (res.data.errcode === -2) {
            Message.error("房间不存在");
          } else {
            Message.error("未知错误");
          }
          /*
                  this.$message({
                    message:res.data,
                    type: 'success'
                  });*/
        })
        .catch(function(error) {
          console.log(error);
        });

    },
    question_change: function(i) {
      this.answer[this.current_question_num].Answer = this.code;
      this.current_question_num = i - 1;
      this.code = this.answer[this.current_question_num].Answer;

    },
    change_high_light: function() {
      this.$message.success("语言更改为" + this.Svalue);
      if (this.Svalue === "html") {
        this.cmOptions.mode = "text/html";
      } else if (this.Svalue === "javascript") {
        this.cmOptions.mode = "text/javascript";
      } else if (this.Svalue === "vue") {
        this.cmOptions.mode = "text/x-vue";
      } else if (this.Svalue === "css") {
        this.cmOptions.mode = "text/css";
      } else if (this.Svalue === "python") {
        this.cmOptions.mode = "text/x-python";
      } else if (this.Svalue === "clike") {
        this.cmOptions.mode = "text/x-c++src";
      } else if (this.Svalue === "sql") {
        this.cmOptions.mode = "text/x-sql";
      } else if (this.Svalue === "sh") {
        this.cmOptions.mode = "text/x-sh";
      } else {
        this.cmOptions.mode = "text/x-java";
      }
    },
    onCmReady: function(cm) {
      console.log("the editor is readied!", cm);
    },

    onCmFocus: function(cm) {
      console.log("the editor is focus!", cm);
    },
    onCmCodeChange: function(newCode) {
      console.log("this is new code", newCode);
      this.code = newCode;
    },
    btn: function() {
      console.log(this.codeV);
      let func = new Function(this.codeV);
      func("dame");
      console.oldLog = console.log;
      console.log = function(str) {
        console.oldLog(str);
        this.lastLog = str;
      };
      func = null;
    }
  },
  computed: {
    codemirror() {
      return this.$refs.myCm.codemirror;
    }
  }


};
</script>

<style scoped>
@import "../../common/stylus/style.css";
@import "../../assets/css/all.css";
@import "../../assets/css/problem_detail.css";
@import "../../assets/css/interview_page.css";
</style>